package util

import (
	"bytes"
	stdlog "log"
	"reflect"
	"unsafe"

	log "github.com/sirupsen/logrus"
)

type sidecarLogFormatter struct {

}

func (f * sidecarLogFormatter) Format(entry *log.Entry) ([]byte, error) {
	buf := &bytes.Buffer{}

	writeString(buf, entry.Time.Format("2006-01-02 15:04:05.000"))
	writeString(buf, " [] ") //不支持trace
	writeString(buf, entry.Level.String())
	writeString(buf, " --- ")
	writeString(buf, "[none] ") //不支持thread id
	writeString(buf, "none ")   //不支持logger name
	writeString(buf, ": ")
	writeString(buf, entry.Message)
	writeString(buf, "\r\n")

	return buf.Bytes(), nil
}

func writeString(buf *bytes.Buffer, str ...string) {
	for _, s := range str {
		buf.Write(stringToBytes(s))
	}
}

func stringToBytes(s string) (data []byte) {

	p := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&s)).Data)
	hdr := (*reflect.SliceHeader)(unsafe.Pointer(&data))

	hdr.Data = uintptr(p)
	hdr.Len = len(s)
	hdr.Cap = len(s)
	return data
}

type stdlogWriter struct {

}

func (w *stdlogWriter) Write(data []byte) (n int, err error) {
	log.Print(string(data))
	return 0, nil
}

func init() {
	log.SetFormatter(&sidecarLogFormatter{})
	stdlog.SetOutput(&stdlogWriter{})
}
